package model;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.CharArraySet;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class AdvancedSearch {

	/**
	 *
	 * @param userQuery
	 * @param play 标题
	 * @param searchField
	 * @param speakerField
	 * @return
	 * @throws Exception
	 */
	public List<Result> search(String userQuery, String play, String searchField, String speakerField)
			throws Exception {
		String index = "index_chinese";
		String field = "contents";
		String playTerm = null;
		String speaker = null;
		if (searchField != null && searchField.trim().length() > 0) {
			field = "contents";index = "index_chinese"; }
		if (play != null && play.trim().length() > 0) { playTerm = "\"" + play + "\""; }
		if (speakerField != null && speakerField.trim().length() > 0 && searchField.equals("Dialogue"))
			{ 	speaker = speakerField; }
		IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
		IndexSearcher searcher = new IndexSearcher(reader);
		Analyzer analyzer=new IKAnalyzer(true,true,false);
		QueryParser parser = null;
		parser = new QueryParser(field, analyzer);
		String searchQuery = "(";
		userQuery = userQuery.trim();
		if (userQuery.indexOf('"')>=0) {//引号内有空格，空格也是查询对象
			searchQuery += field + ":" + userQuery;
		} else { StringTokenizer t = new StringTokenizer(userQuery);//按照空格分词
			searchQuery += "(";
			while (t.hasMoreTokens()) { String token = t.nextToken();
				if (token.equals("AND") || token.equals("OR") || token.equals("NOT")) {
					searchQuery += token + " ";
				} else { searchQuery += field + ":" + token.trim() + " "; }
			}searchQuery += ")";
		}searchQuery += ")";
		if (playTerm != null) { searchQuery = searchQuery + " AND title:" + playTerm + ""; }
		if (speaker != null) { searchQuery = searchQuery + " AND speaker:" + speaker; }
		//已经生成searchQuery
		System.out.println("SearchQ : " + searchQuery);
		Query query = parser.parse(searchQuery);//搜索内容分词
		System.out.println("Searching for: " + query.toString(field));
		return doSearch(searcher, query, searchField);//query：查询内容分词
	}

	public List<Result> doSearch(IndexSearcher searcher, Query query, String type) throws IOException {
		List<String> headers=new ArrayList<>();
		List<Result> resultList = new ArrayList<Result>();
		TopDocs results = searcher.search(query, Integer.MAX_VALUE);//需要解析的结构化查询结果
		ScoreDoc[] hits = results.scoreDocs;//查询结果数组
		int numTotalHits = results.totalHits;//命中个数
		System.out.println("HITS:" + numTotalHits);
		for (int i = 0; i < numTotalHits; i++) {
			Result r = new Result();//Result自定义目录结果显示结构
			r.setResultType("All");
			Document doc = searcher.doc(hits[i].doc);
			r.setPath(doc.get("path"));
			r.setTitle(doc.get("title"));
			r.setAct(doc.get("act"));
			r.setScene(doc.get("scene"));
			r.setSpeaker(doc.get("speaker"));
			String head=doc.get("act")+doc.get("scene")+doc.get("speaker");
			if(!headers.contains(head)) {
				//System.out.println(doc.get("stagedir"));
				System.out.println((i + 1) + ". " + r.toString());
				resultList.add(r);
				headers.add(head);
			}
		}
		return resultList;
	}
}
